import json
import logging
import urllib
from typing import Union

import requests
from requests.cookies import RequestsCookieJar
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from user_agent import generate_user_agent

from sam import chrome_driver_path

requests.packages.urllib3.disable_warnings()

logging.getLogger("requests").setLevel(logging.WARNING)
logging.getLogger("urllib3").setLevel(logging.WARNING)


# def request(flow: mitmproxy.http.HTTPFlow):
#     global num
#     num = num + 1
#     ctx.log.info("We've seen %d flows" % num)


def http_get(url, param=None, cookies: Union[dict, RequestsCookieJar] = None, proxies: dict = None,
             header: dict = None):
    if not header:
        header = {"User-Agent": generate_user_agent(), "Referer": url}
    return requests.get(url, params=param, headers=header, cookies=cookies, proxies=proxies, verify=False)


def http_post(url, data=None, optional: str = None, cookies: Union[dict, RequestsCookieJar] = None,
              proxies: dict = None, header: dict = None):
    if not header:
        header = {"User-Agent": generate_user_agent(), "Referer": url}
    if "json" == optional:
        resp = requests.post(url, json=data, headers=header, cookies=cookies, proxies=proxies, verify=False)
        return json.loads(resp.text)
    else:
        return requests.post(url, data=data, headers=header, cookies=cookies, proxies=proxies, verify=False)


def http_post_json(url, data):
    return http_post(url, data=data, optional="json")


def http_put(url, data):
    return requests.put(url, data=data, verify=False)


def http_delete(url):
    return requests.delete(url)


# jar = requests.cookies.RequestsCookieJar()
# jar.set('tasty_cookie', 'yum', domain='httpbin.org', path='/cookies')
# jar.set('gross_cookie', 'blech', domain='httpbin.org', path='/elsewhere')


def get_url_encode_str(s: str):
    return urllib.parse.quote(s, safe='/', encoding="utf8", errors=None)


def get_url_decode_str(s: str):
    return urllib.parse.unquote(s, encoding="utf8", errors='replace')


def get_web_driver(headless: bool = True, images_less: bool = True):
    '''
    初始化一个无图形 浏览器
    :return:
    '''
    chrome_options = Options()
    # 设置chrome浏览器无界面模式
    # 浏览器不提供可视化页面. linux下如果系统不支持可视化不加这条会启动失败
    if headless:
        chrome_options.add_argument('--headless')
    # 不加载图片, 提升速度
    if images_less:
        chrome_options.add_argument('blink-settings=imagesEnabled=false')
    # 添加请求头
    chrome_options.add_argument('--user-agent={}'.format(generate_user_agent()))
    # Chrome driver default setting under Windows OS
    # chrome_options.add_argument('--disable-gpu')

    # print(chrome_options.arguments)
    # 实例化一个浏览器
    # global driver
    return webdriver.Chrome(options=chrome_options, executable_path=chrome_driver_path)


def load_jquery(browser):
    browser.execute_script("""
        var head = document.getElementsByTagName('head')[0];
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = "https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js";
        head.appendChild(script);
        """)


def main2():
    driver = get_web_driver()
    # 发送请求
    driver.get("https://www.baidu.com/")

    # 页面截屏
    # driver.save_screenshot('./baidu.png')

    # id="kw"是百度搜索输入框，输入字符串"长城"
    driver.find_element_by_id("kw").send_keys("长城")

    # id="su"是百度搜索按钮，click() 是模拟点击
    driver.find_element_by_id("su").click()

    # 打印页面源代码
    # print(driver.page_source)

    # 关闭chreomedriver进程
    driver.quit()


def test2():
    s = "%23%E4%BD%A0%E6%86%A7%E6%86%AC%E4%BB%80%E4%B9%88%E6%A0%B7%E7%9A%84%E5%A4%A7%E5%AD%A6%E7%94%9F%E6%B4%BB%23"
    ss = f"{get_url_encode_str('#你憧憬什么样的大学生活#')}"
    print(s)
    print(ss)


def test3():
    url = "https://cn.bing.com/search?q=addon&aqs=edge..69i57j69i65&FORM=ANCMS9&PC=U531"
    get = requests.session().get(url=url)
    print(get)


if __name__ == '__main__':
    test3()
    print('end')
